package woaini.wind.bot.ai.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson2.JSONObject;
import com.coze.openapi.client.files.UploadFileReq;
import com.coze.openapi.client.files.UploadFileResp;
import com.coze.openapi.client.workflows.run.RunWorkflowReq;
import com.coze.openapi.client.workflows.run.RunWorkflowResp;
import com.coze.openapi.service.service.CozeAPI;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import woaini.wind.bot.ai.dao.AiFaceTemplateRepository;
import woaini.wind.bot.chat.config.CozeChatterConfig;

import java.io.IOException;

@Service
@Slf4j
@RequiredArgsConstructor
public class AiChangeFaceService {

  private final AiFaceTemplateRepository aiFaceTemplateRepository;
  private final CozeAPI cozeAPI;

  public JSONObject faceChange(MultipartFile template, MultipartFile image) {

    String singleId;
    try {
      singleId = SecureUtil.md5(template.getInputStream());
    } catch (IOException e) {
      throw new RuntimeException("文件流异常!!!");
    }
    // 进行文件上传
    String templateId = null;
    String imageId;
    if (StrUtil.isNotEmpty(singleId)) {
      templateId = aiFaceTemplateRepository.findFaceIdByMd5Id(singleId);
    }
    if (StrUtil.isEmpty(templateId)) {
      templateId  = this.upload(template);
    }
    imageId = this.upload(image);

    templateId = STR."{\"file_id\":\"\{templateId}\"}";
    imageId = STR."{\"file_id\":\"\{imageId}\"}";


    // 调用工作流
    RunWorkflowReq workflowReq = RunWorkflowReq.builder()
      .workflowID("7545109338760757289")
      .parameters(JSONObject.of("template", templateId, "image", imageId))
      .build();

    RunWorkflowResp runWorkflowResp = cozeAPI.workflows().runs().create(workflowReq);

    log.info("结果: {}", JSONObject.toJSONString(runWorkflowResp));

    return JSONObject.parseObject(runWorkflowResp.getData());
  }

  /**
   * 上传
   *
   * @param file 文件
   * @author yefeng {@date 2025-09-10 09:35:32}
   * @since 1.0
   * @return {@link String }
   */
  private String upload(MultipartFile file) {

    try {
      UploadFileReq req = UploadFileReq.of(file.getName(), file.getBytes());
      UploadFileResp upload = cozeAPI.files().upload(req);
      return upload.getFileInfo().getID();
    } catch (IOException e) {
      throw new RuntimeException("文件上传异常");
    }
  }
}
